//
//  NetworkTool.m
//  
//
//  Created by admin on 17/3/2.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "NetworkTool.h"
#import <AFNetworking.h>

@implementation NetworkTool
{
    AFHTTPSessionManager *_manager;
}
+ (instancetype)sharedInstance {
    
    static NetworkTool *instance;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // 子类调用父类的实例化的方法
        instance = [self new];
    });
    
    return instance;
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        _manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:@"http://toutiao.inping.com/"] sessionConfiguration:config];
        // 2.1 允许无效证书
        _manager.securityPolicy.allowInvalidCertificates = YES;
        // 2.2 不验证域名
        _manager.securityPolicy.validatesDomainName = NO;
        // 2.3 增加AFN支持的文件类型
        
        _manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", @"text/html",nil];
        // 2.4 让AFN返回原始的二进制数据
        _manager.responseSerializer = [AFHTTPResponseSerializer serializer];//格式和上面的一致
        //        _manager.requestSerializer = [AFJSONRequestSerializer serializer];//json格式
        _manager.requestSerializer.timeoutInterval = 5.0;
    }
    return self;
}

- (void)GETWithUrlString:(NSString *)urlString parameters:(id)parameters success:(void (^)(id))successBlock failure:(void (^)(NSError *))failureBlock {
 
    [_manager GET:urlString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // 把AFN获取的responseObject,回调给外界
        if (successBlock) {
            successBlock(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failureBlock) {
            failureBlock(error);
        }
    }];
}

- (void)POSTWithUrlString:(NSString *)urlString parameters:(id)parameters success:(void (^)(id))successBlock failure:(void (^)(NSError *))failureBlock {
    
    [_manager POST:urlString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // 把AFN获取的responseObject,回调给外界
        if (successBlock) {
            successBlock(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failureBlock) {
            failureBlock(error);
        }
    }];
}

#pragma mark -2017年11月13日 新的云头条api  接口 POST
- (void)PostYunTouTiaoWithUrlString:(NSString *)urlString input:(id)input success:(void (^)(NSDictionary *))successBlock failure:(void (^)(NSError *))failureBlock {
    if ([urlString isEqualToString:GET_GRCODE_URL] || [urlString isEqualToString:GET_MBCODE_URL]) {
        [_UserM setUsercode:@""];
    }
    [_UserM hmacSHA256ShouQuanJiamiWithUserCode:[_UserM usercode]];
    
    NSString *inputStr = [_UserM dictionaryToJson:input];
    
    NSString *signature = [_UserM hmac:inputStr withKey:[_UserM accesskey]];
    NSDictionary * jsonDic = @{
                               @"appkey":APPKEY,
                               @"input":inputStr,
                               @"signature":signature,
                               @"usercode":[_UserM usercode],
                               @"ip":[NNDeviceInformation getDeviceIPAdress],
                               @"times":_UserM.times
                               };
    NSString *jsonStr = [_UserM dictionaryToJson:jsonDic];
    NSData *data = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSString *jsonDicStr = [data base64EncodedStringWithOptions:0];
    [[NetworkTool sharedInstance] POSTWithUrlString:urlString parameters:@{@"data":jsonDicStr} success:^(id responseObject) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:NULL];
        if (successBlock) {
            successBlock(dict);
        }
    } failure:^(NSError *error) {
        if (failureBlock) {
            failureBlock(error);
        }
    }];
}

#pragma mark -  新的api  接口 upload
//- (void)uploadFuYinWithUrlString:(NSString *)urlString input:(id)input success:(void (^)(NSDictionary *))successBlock failure:(void (^)(NSError *))failureBlock {
-(void)uploadYunTouTiaoWithUrlString:(NSString *)urlString input:(id)input dataImage:(NSData *)dataImage filePath:(NSString *)filePath success:(void (^)(NSDictionary *))successBlock failure:(void (^)(NSError *))failureBlock
{
    // 1.地址
    // 要发送给服务器的文字信息 : 服务器提供key (服务器接受文字信息的字段名)
    
    if ([urlString isEqualToString:GET_GRCODE_URL] || [urlString isEqualToString:GET_MBCODE_URL]) {
        [_UserM setUsercode:@""];
    }
    [_UserM hmacSHA256ShouQuanJiamiWithUserCode:[_UserM usercode]];
    
    NSString *inputStr = [_UserM dictionaryToJson:input];
    
    NSString *signature = [_UserM hmac:inputStr withKey:[_UserM accesskey]];
    NSDictionary * jsonDic = @{
                               @"appkey":APPKEY,
                               @"input":inputStr,
                               @"signature":signature,
                               @"usercode":[_UserM usercode],
                               @"ip":@"0",
                               @"times":_UserM.times
                               };
    NSString *jsonStr = [_UserM dictionaryToJson:jsonDic];
    NSData *data = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSString *jsonDicStr = [data base64EncodedStringWithOptions:0];
    
    // 3.网络会话管理者发送POST请求
    /*
     参数1 : 请求地址
     参数2 : 请求参数
     参数3 : 拼接请求体的回调
     参数4 : 进度回调
     参数5 : 成功回调
     参数6 : 失败回调
     */
    [[NetworkTool sharedInstance] POST:urlString parameters:@{@"data":jsonDicStr} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        // 用于拼接请求体
        /*
         参数1 : 要上传的文件二进制
         参数2 : 服务器接受文件字段名 (由服务器提供)
         参数3 : 文件保存在服务器的文件名
         参数4 : 要上传的文件的类型
         */
        
        NSLog(@"%@",filePath);
        // 拼接请求体
        [formData appendPartWithFileData:dataImage name:@"file" fileName:[filePath lastPathComponent] mimeType:@"image/jpg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        // 获取长传图片的进度
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //请求的结果
        NSLog(@"%@ %@",[responseObject class],responseObject);
        if (successBlock) {
            successBlock(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failureBlock) {
            failureBlock(error);
        }
    }];
}

@end
